package rest

import (
	"errors"
	"fmt"
	"log"
	"net/url"
	"os"
	"path/filepath"

	"picture/config"
	"picture/util"

	"github.com/gin-gonic/gin"
)

func GetPicture() {
	router := gin.Default()
	router.MaxMultipartMemory = 8 << 21
	//最大为16M
	router.POST("/uploadPicture", tokenUpload)
	router.POST("/localuploadPicture", localUpload)
	router.POST("/localUploadMultiPicture", localUploadMultiPicture)
	router.POST("/localRemoveMutilPicture", localRemoveMutilPicture)
	router.Run(":8081")

}
func localUpload(c *gin.Context) {
	file, err := c.FormFile("picture")
	var NewFilename string
	if err != nil {
		c.String(400, err.Error()+"获取文件失败")
	}
	NewFilename = util.Hash(file.Filename)
	extension := filepath.Ext(file.Filename)

	dst := config.GlobalConfig.Router.Picture + NewFilename + extension
	fmt.Println(dst)
	c.SaveUploadedFile(file, dst)
	c.String(200, config.GlobalConfig.Router.PictureServer+NewFilename+extension)
}

func tokenUpload(c *gin.Context) {
	file, err := c.FormFile("file")
	var NewFilename string
	if err != nil {
		c.String(400, err.Error()+"获取文件失败")
		return
	}
	token := c.PostForm("token")
	if _, err := util.ParseToken(token); err != nil {
		c.String(400, "解析Token出错"+err.Error())
		return
	} else {

		NewFilename = util.Hash(file.Filename)
		extension := filepath.Ext(file.Filename)
		dst := config.GlobalConfig.Router.Picture + NewFilename + extension
		fmt.Println(dst)
		c.SaveUploadedFile(file, dst)
		c.String(200, config.GlobalConfig.Router.PictureServer+NewFilename+extension)
	}
}
func localUploadMultiPicture(c *gin.Context) {
	form, err := c.MultipartForm()
	if err != nil {
		c.JSON(400, gin.H{"error": "图片服务器接受图片失败"})
		return
	}
	files := form.File["file"]
	var allUrl []string
	for _, file := range files {
		NewFilename := util.Hash(file.Filename)
		extension := filepath.Ext(file.Filename)
		dst := config.GlobalConfig.Router.Picture + NewFilename + extension
		fmt.Println(dst)
		c.SaveUploadedFile(file, dst)
		allUrl = append(allUrl, config.GlobalConfig.Router.PictureServer+NewFilename+extension)
	}
	c.JSON(200, gin.H{"allUrl": allUrl})
}

// 值得注意的是，在这里输入的是url，而需要删除的是dst
func localRemoveMutilPicture(c *gin.Context) {
	var allUrl []string
	form, err := c.MultipartForm()
	if err != nil {
		c.JSON(400, gin.H{"error": "图片服务器接受需要删除的图片失败"})
		log.Println("严重错误!,有图片上传成功了，但是并没有被删除")
		return
	}
	allUrl = form.Value["url"]
	for index, url := range allUrl {
		err := deletePicture(url)
		if err != nil {
			c.JSON(400, gin.H{"error": "图片服务器删除图片时失败，可能是给出的图片名称"})
			log.Println("严重错误!,有图片上传成功了，但是删除的时候发现删到" + fmt.Sprintf("%d", index) + "张的时候删除失败")
			return
		}
	}
	c.JSON(200, gin.H{"message": "success"})
}
func deletePicture(fileUrl string) error {

	parsedURL, err := url.Parse(fileUrl)
	if err != nil {
		log.Println("严重错误，解析照片url位dst失败")
		return errors.New("Error parsing URL:" + err.Error())
	}

	// 提取文件名
	fileName := filepath.Base(parsedURL.Path)

	// 构建文件的完整路径
	dst := filepath.Join(config.GlobalConfig.Router.Picture, fileName)
	err = os.Remove(dst)
	return err
}
